import paramiko
import time
import tkinter as tk
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def execute_program():
    IPdri = selected_option.get()
    passw = password_entry.get()

    browser = webdriver.Edge()
    browser.maximize_window()

    browser.get(f'http://{IPdri}')

    print(browser.title)
    browser.find_element(By.NAME, "router_password").send_keys(passw)
    browser.find_element(By.CLASS_NAME, "btn-login").click()

    time.sleep(2)
    current_url = browser.current_url
    print("当前网址：", current_url)

    new_url = current_url.replace("/web/home#router", "/api/misystem/extendwifi_connect?ssid=abc&password=12345678")
    print("替换后的网址：", new_url)
    browser.get(new_url)

    new_url = current_url.replace("/web/home#router", "/api/xqsystem/oneclick_get_remote_token?username=xxx&password=xxx&nonce=xxx")
    print("替换后的网址：", new_url)
    browser.get(new_url)
    browser.quit()
    print("网页部分操作完毕，开始ssh登录")

    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh_client.connect(hostname=IPdri, port=22, username='root', password=passw)

    shell = ssh_client.invoke_shell()

    commands = [
        'cd /tmp',
        'curl -k -O https://router.zl1006.com/CR660X/pb-boot.img',
        'mtd write /tmp/pb-boot.img Bootloader',
        'reboot'
    ]

    for command in commands:
        time.sleep(1)
        shell.send(command + '\n')
        print(command)
        output = shell.recv(4096).decode('utf-8')
        print(output)
        time.sleep(2)

    shell.close()
    ssh_client.close()
    result_label.config(text="刷机完毕")

def on_select(option):
    selected_option.set(option)

# 创建GUI窗口
window = tk.Tk()
window.title("刷机程序")
window.geometry("400x200")

#---------------------------------------------
# 定义选项列表
options = ["192.168.10.1", "192.168.31.1", "192.168.2.1", "选择路由的IP地址"]

# 创建下拉框变量
selected_option = tk.StringVar(window)
selected_option.set(options[3])  # 默认选择第一个选项

# 创建下拉框
option_menu = tk.OptionMenu(window, selected_option, *options, command=on_select)
option_menu.pack()
#-----------------------------------------

# 创建密码输入框和标签
password_label = tk.Label(window, text="密码:")
password_label.pack()
password_entry = tk.Entry(window, show="")
password_entry.pack()

# 创建执行按钮
execute_button = tk.Button(window, text="刷机", command=execute_program)
execute_button.pack()

# 创建结果标签
result_label = tk.Label(window, text="")
result_label.pack()

window.mainloop()
